//
//  XMRechargeViewController.m
//  MyNewProject
//
//  Created by ZhangYuan on 2019/1/30.
//  Copyright © 2019年 sun. All rights reserved.
//

#import "XMRechargeViewController.h"
#import "XMAccountDetailViewController.h"
#import <AlipaySDK/AlipaySDK.h>


#pragma mark -- mark 数据相关
#import "WJRechargeModel.h"
#import "UserInfoModel.h"

@interface XMRechargeViewController () {
    UIButton *_segmentBtn1;
    UIButton *_segmentBtn2;
    
    UIButton *_aliPayBtn;
    UIButton *_wxPayBtn;
    UIButton *_balancePayBtn;
    UILabel *_label6; // 余额支付/保证金支付
    
    NSString *_rechargeStyle; // 充值方式 1 支付宝 2 微信 3 余额
}
@property(nonatomic , retain)UILabel * balanceLabel;
@property(nonatomic , retain)UITextField * moneyNum;//金额
@property(nonatomic , retain)UIImageView * chosedImg;//选择提示
@property(nonatomic , retain)UIView * whiteView;
@property (nonatomic, copy) NSString *rechargeType; // 充值类型 1金额2保证金
@end

@implementation XMRechargeViewController

static int count = 1;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navigationBar.hidden = NO;
    self.gk_navTitle = @"充值中心";
    self.view.backgroundColor = BackColor;
    [self initContentViews];
    [self getUserInfo];
}
- (void)initContentViews {
    // 余额
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(SKTopBar_Height + 20);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(46.0/667);
    }];
    
    // 保证金
    UIView *view2 = [[UIView alloc] init];
    view2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view2];
    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(view1);
        make.top.mas_equalTo(view1.mas_bottom).mas_offset(0.5);
    }];
    
    // 充值金额
    UIView *view3 = [[UIView alloc] init];
    view3.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view3];
    [view3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(view1);
        make.top.mas_equalTo(view2.mas_bottom).mas_offset(10);
    }];
    
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.font = SKFONT_BOLD_SIZE(18);
    tipLabel.textColor = SKColorWithHex(0x444444);
    tipLabel.text = @"    请选择支付方式";
    tipLabel.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(view1);
        make.top.mas_equalTo(view3.mas_bottom).mas_offset(10);
    }];
    /*
    // 支付宝
    UIView *view4 = [[UIView alloc] init];
    view4.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view4];
    [view4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(view1);
        make.top.mas_equalTo(tipLabel.mas_bottom);
    }];
    */
    // 微信
    UIView *view5 = [[UIView alloc] init];
    view5.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view5];
    [view5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(view1);
        make.top.mas_equalTo(tipLabel.mas_bottom);
    }];
    
    // 余额支付
    UIView *view6 = [[UIView alloc] init];
    view6.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view6];
    [view6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(view1);
        make.top.mas_equalTo(view5.mas_bottom);
    }];
    
    UILabel *label1 = [[UILabel alloc] init];
    label1.text = @"余额";
    label1.font = SKFONT_SIZE(13);
    label1.textColor = SKColorWithHex(0x333333);
    [view1 addSubview:label1];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setImage:SKIMAGE_NAMED(@"mine_pay_choose_unselect_btn_img") forState:UIControlStateNormal];
    [btn1 setImage:SKIMAGE_NAMED(@"mine_pay_choose_select_btn_img") forState:UIControlStateSelected];
    [btn1 addTarget:self action:@selector(segmentButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view1 addSubview:btn1];
    
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.top.bottom.mas_offset(0);
    }];
    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-16);
        make.centerY.mas_offset(0);
        make.top.mas_offset(6);
        make.bottom.mas_offset(-6);
        make.width.mas_equalTo(btn1.mas_height);
    }];
    
    UILabel *label2 = [[UILabel alloc] init];
    label2.text = @"保证金";
    label2.font = SKFONT_SIZE(13);
    label2.textColor = SKColorWithHex(0x333333);
    [view2 addSubview:label2];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setImage:SKIMAGE_NAMED(@"mine_pay_choose_unselect_btn_img") forState:UIControlStateNormal];
    [btn2 setImage:SKIMAGE_NAMED(@"mine_pay_choose_select_btn_img") forState:UIControlStateSelected];
    [btn2 addTarget:self action:@selector(segmentButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view2 addSubview:btn2];
    
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.top.bottom.mas_offset(0);
    }];
    [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-16);
        make.centerY.mas_offset(0);
        make.size.mas_equalTo(btn1);
    }];
    _segmentBtn1 = btn1;
    _segmentBtn2 = btn2;
    
    
    UILabel *label3 = [[UILabel alloc] init];
    label3.text = @"金额";
    label3.font = SKFONT_SIZE(13);
    label3.textColor = SKColorWithHex(0x333333);
    [view3 addSubview:label3];
    
    UITextField *textField3 = [[UITextField alloc] init];
    textField3.placeholder = @"请输入充值金额";
    textField3.keyboardType = UIKeyboardTypeDecimalPad;
    textField3.font = SKFONT_Medium(15);
    [view3 addSubview:textField3];
    self.moneyNum = textField3;
    
    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(label2);
        make.top.bottom.mas_offset(0);
        make.width.mas_equalTo(40);
    }];
    [textField3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(label3.mas_right).mas_offset(16);
        make.right.mas_offset(-16);
        make.top.mas_offset(8);
        make.centerY.mas_offset(0);
    }];

    /*
    UIImageView *imageView4 = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"mine_payment_alipay_type_img")];
    [view4 addSubview:imageView4];
    
    UILabel *label4 = [[UILabel alloc] init];
    label4.text = @"支付宝支付";
    label4.textColor = SKColorWithHex(0x333333);
    label4.font = SKFONT_Medium(13);
    [view4 addSubview:label4];
    
    UIButton *btn4 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn4 setImage:SKIMAGE_NAMED(@"mine_pay_choose_unselect_btn_img") forState:UIControlStateNormal];
    [btn4 setImage:SKIMAGE_NAMED(@"mine_pay_choose_select_btn_img") forState:UIControlStateSelected];
    [btn4 addTarget:self action:@selector(rechargeTypeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view4 addSubview:btn4];
    
    [imageView4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.top.mas_offset(6);
        make.bottom.mas_offset(-6);
        make.width.mas_equalTo(imageView4.mas_height);
    }];
    
    [label4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(imageView4.mas_right).mas_offset(10);
        make.top.bottom.mas_offset(0);
    }];
    
    [btn4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(btn1);
        make.centerY.mas_offset(0);
        make.size.mas_equalTo(btn1);
    }];
    */
    UIImageView *imageView5 = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"mine_payment_wx_type_img")];
    [view5 addSubview:imageView5];
    
    UILabel *label5 = [[UILabel alloc] init];
    label5.text = @"微信支付";
    label5.textColor = SKColorWithHex(0x333333);
    label5.font = SKFONT_Medium(13);
    [view5 addSubview:label5];
    
    UIButton *btn5 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn5 setImage:SKIMAGE_NAMED(@"mine_pay_choose_unselect_btn_img") forState:UIControlStateNormal];
    [btn5 setImage:SKIMAGE_NAMED(@"mine_pay_choose_select_btn_img") forState:UIControlStateSelected];
    [btn5 addTarget:self action:@selector(rechargeTypeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view5 addSubview:btn5];
    
    [imageView5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.top.mas_offset(6);
        make.bottom.mas_offset(-6);
        make.width.mas_equalTo(imageView5.mas_height);
    }];
    
    [label5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(imageView5.mas_right).mas_offset(10);
        make.top.bottom.mas_offset(0);
    }];
    
    [btn5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(btn1);
        make.centerY.mas_offset(0);
        make.size.mas_equalTo(btn1);
    }];
    
    
    UIImageView *imageView6 = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"mine_payment_balance_type_img")];
    [view6 addSubview:imageView6];
    
    UILabel *label6 = [[UILabel alloc] init];
    label6.text = @"余额支付";
    label6.textColor = SKColorWithHex(0x333333);
    label6.font = SKFONT_Medium(13);
    [view6 addSubview:label6];
    _label6 = label6;
    
    UIButton *btn6 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn6 setImage:SKIMAGE_NAMED(@"mine_pay_choose_unselect_btn_img") forState:UIControlStateNormal];
    [btn6 setImage:SKIMAGE_NAMED(@"mine_pay_choose_select_btn_img") forState:UIControlStateSelected];
    [btn6 addTarget:self action:@selector(rechargeTypeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view6 addSubview:btn6];
    
    [imageView6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.top.mas_offset(6);
        make.bottom.mas_offset(-6);
        make.width.mas_equalTo(imageView5.mas_height);
    }];
    
    [label6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(imageView6.mas_right).mas_offset(10);
        make.top.bottom.mas_offset(0);
    }];
    
    [btn6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(btn1);
        make.centerY.mas_offset(0);
        make.size.mas_equalTo(btn1);
    }];
//    _aliPayBtn = btn4;
    _wxPayBtn = btn5;
    _balancePayBtn = btn6;
    
    UIButton *rechargeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rechargeBtn setTitle:@"充 值" forState:UIControlStateNormal];
    rechargeBtn.titleLabel.font = SKFONT_BOLD_SIZE(15);
    rechargeBtn.backgroundColor = SKColorWithHex(0xE33030);
    [rechargeBtn addTarget:self action:@selector(rechargeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rechargeBtn];
    [rechargeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(49.0/667);
        make.bottom.mas_offset(-SKBottomSafe_Height);
    }];
    
    UILabel *balanceLabel = [[UILabel alloc] init];
    balanceLabel.textColor = SKColorWithHex(0x999999);
    balanceLabel.font = SKFONT_Medium(14);
    balanceLabel.textAlignment = NSTextAlignmentRight;
    [view6 addSubview:balanceLabel];
    
    UIButton *balanceRechargeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [balanceRechargeBtn setTitle:@"充值" forState:UIControlStateNormal];
    balanceRechargeBtn.titleLabel.font = SKFONT_BOLD_SIZE(14);
    [balanceRechargeBtn setTitleColor:SKColorWithHex(0xE33030) forState:UIControlStateNormal];
    [balanceRechargeBtn addTarget:self action:@selector(rechargeBalanceButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view6 addSubview:balanceRechargeBtn];
    balanceRechargeBtn.hidden = true;
    [balanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-45);
        make.top.bottom.mas_offset(0);
    }];
    [balanceRechargeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(balanceLabel.mas_left).mas_offset(-16);
        make.centerY.mas_offset(0);
    }];
    _balanceLabel = balanceLabel;
}


#pragma mark -- mark EVENT

- (void)segmentButtonClick:(UIButton *)sender {
    [self getUserInfo];
    sender.selected = true;
    if (sender == _segmentBtn1) {
        _segmentBtn2.selected = false;
        // 余额
        _rechargeType = @"1";
        // 切换余额支付 为 保证金支付
        // 保证金充值 余额
        _label6.text = @"保证金支付";
    }else {
        _segmentBtn1.selected = false;
        // 保证金
        _rechargeType = @"2";
        // 切换保证金支付 为 余额支付
        // 余额充值保证金
        _label6.text = @"余额支付";
    }
}

/// 充值方式选择
/// @param sender sender
- (void)rechargeTypeButtonClick:(UIButton *)sender {
    _aliPayBtn.selected = false;
    _wxPayBtn.selected = false;
    _balancePayBtn.selected = false;
    sender.selected = true;
    if (sender == _aliPayBtn) {
        _rechargeStyle = @"1";
    }else if (sender == _wxPayBtn) {
        _rechargeStyle = @"2";
    }else if (sender == _balancePayBtn) {
        _rechargeStyle = @"3";
    }else {}
}

/// 充值去
/// @param sender sender
- (void)rechargeButtonClick:(UIButton *)sender {
    if (!(_rechargeStyle && _rechargeType)) {
        return; }
    if ([self.moneyNum.text floatValue] <= 0) {
        return; }
    if ([_rechargeStyle isEqualToString:@"1"]) {
        // 支付宝
        [self alipay];
    }else if ([_rechargeStyle isEqualToString:@"2"]) {
        // 微信支付
        [self wxPay];
    }else if ([_rechargeStyle isEqualToString:@"3"]) {
        if ([_rechargeType isEqualToString:@"1"]) {
            // 保证金充值余额
            [self baozhengjinPayToBalance];
        }else if ([_rechargeType isEqualToString:@"2"]) {
            // 余额充值保证金
            [self balancePayToBaozhengjin];
        }else {}
    }else {}
}

/**
 充值余额

 @param sender sender
 */
- (void)rechargeBalanceButtonClick:(UIButton *)sender {
    
}

-(void)selectDeal:(UIButton *)sender
{
    [self.view endEditing:YES];

    for (int i = 0; i<count; i++) {

        UIImageView * imageView =[_whiteView viewWithTag:111111111 *2 + i];
        if (sender.tag - 111111111 == i) {
            imageView.image =SKIMAGE_NAMED(@"selectedItem");
        }
        else
        {
            imageView.image =SKIMAGE_NAMED(@"unSelectedItem");
        }
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark -- mark 支付

- (void)alipay {
    NSDictionary *param = @{@"uid":self.uid,
                            @"loginKey":self.loginKey,
                            @"money":[NSString stringWithFormat:@"%f", [self.moneyNum.text floatValue]],
                            @"money_type":_rechargeType
    };
    SKWeakSelf;
    [YQNetworking postWithUrl:@"pay/alipay" refreshRequest:YES cache:NO params:param progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if ([response[@"status"] isEqualToString:@"ok"]) {
            [weakSelf getUserInfo];
            [[AlipaySDK defaultService] payOrder:SafeString(response[@"data"]) fromScheme:@"YPYXOpenUrl" callback:^(NSDictionary *resultDic) {
                [weakSelf showMessage:@"充值成功"];
            }];
        }else {
            [weakSelf showMessage:response[@"msg"]];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}
- (void)wxPay {
    NSDictionary *param = @{@"uid":self.uid,
                            @"loginKey":self.loginKey,
                            @"money":[NSString stringWithFormat:@"%f", [self.moneyNum.text floatValue]],
                            @"money_type":_rechargeType
    };
    SKWeakSelf;
    [YQNetworking postWithUrl:@"pay/weixinpay" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        WJRechargeModel *model = [WJRechargeModel modelWithDictionary:response];
        if ([model isSuccess]) {
            [weakSelf wxPayWith:model.data And:param];
        }else {
            [weakSelf showMessage:model.msg];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}
- (void)wxPayWith:(WJWXRechargeModel *)model And:(NSDictionary *)info {
    SKWeakSelf;
    [AppDelegate wj_payrequestWithNonceStr:model.noncestr Package:model.package Partnerid:model.partnerid Prepayid:model.prepayid Timestamp:model.timestamp Sign:model.sign Complete:^(BOOL success) {
        if (success) {
            [weakSelf getUserInfo];
            // 充值成功
            if (weakSelf.paySuccessResultBlock) {
                weakSelf.paySuccessResultBlock();
            }
        }else {
            // 充值失败
            [weakSelf showMessage:model.msg];
        }
    }];
}

- (void)balancePayToBaozhengjin {
    NSDictionary *param = @{@"uid":self.uid,
                            @"loginKey":self.loginKey,
                            @"bail":@([self.moneyNum.text floatValue])
    };
    SKWeakSelf;
    [YQNetworking postWithUrl:@"pay/moneyChangeBail" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        WJBaseModel *model = [WJBaseModel modelWithDictionary:response];
        [weakSelf showMessage:model.msg];
        if ([model isSuccess]) {
            [weakSelf getUserInfo];
        }else {
            [weakSelf showMessage:model.msg];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}

- (void)baozhengjinPayToBalance {
    NSDictionary *param = @{@"uid":self.uid,
                            @"loginKey":self.loginKey,
                            @"money":@([self.moneyNum.text floatValue])
                            };
    SKWeakSelf;
    [YQNetworking postWithUrl:@"pay/bailChangeMoney" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        WJBaseModel *model = [WJBaseModel modelWithDictionary:response];
        [weakSelf showMessage:model.msg];
        if ([model isSuccess]) {
            [weakSelf getUserInfo];
        }else {
            [weakSelf showMessage:model.msg];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}

// 获取余额信息
- (void)getUserInfo {
    NSDictionary *param = @{
                            @"uid":self.uid,
                            @"loginKey":self.loginKey
                            };
    SKWeakSelf;
    [YQNetworking getWithUrl:@"my/getUserInfo" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        UserInfoModel *model = [UserInfoModel modelWithDictionary:response];
        if ([model isSuccess]) {
            if ([weakSelf.rechargeType isEqualToString:@"1"]) {
                // 保证金充值余额 展示保证金
                weakSelf.balanceLabel.text = [NSString stringWithFormat:@"可用余额：%@元", model.user_info.keyong_bail];
            }else if ([weakSelf.rechargeType isEqualToString:@"2"]) {
                // 余额充值保证金 展示余额
                weakSelf.balanceLabel.text = [NSString stringWithFormat:@"可用余额：%@元", model.user_info.keyong_yue];
            }else {}
            YPLoginUserInfo *info = [YPLoginUserInfo modelObjectWithDictionary: model.user_info.modelToJSONObject];
            [UserInfoSingleton shareInstance].userInfo = info;
            SKUserUserDefaults_Save(response[@"user_info"] , @"UserInfo");
        }else {
            
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}
@end
